<?php
namespace Admin\Controller;

use Think\Controller;

class UserController extends Controller{
    private $user;

    function __construct()
    {
        parent :: __construct();
        $this->user = M('User');
    }


    public function register(){
        $this->display();
    }

    public function do_register(){
        $user = D("User");
        if(!$user->create()){
            $this->error($user->getError());
        }else{
            $user->add();
//            dump($user->getLastSql());
//            exit;
            $this->success('注册成功',U('login'));
        }
    }

    function login(){
        $this->display();
    }
    function do_login(){
        $code = I("post.code");
        if(!$this->check_verify($code)){
            $this->error('验证码错误');
        }

        $data['email'] = I("post.email");
        $data['password'] = md5(trim(I("post.password")));

        $user = $this->user->where($data)->find();
//        dump($this->user->getLastSql());
//        exit;
        if(!$user){
            $this->error('用户名或密码错误');
        }
//        dump($user);
//        exit;
        $rem = I('post.rem');
        if(isset($rem)){
            setcookie('token', $user['token'], time() + 60 * 60 * 24 * 7, '/');
        }else{
            setcookie('token', $user['token'], null, '/');
        }

        $_SESSION['user'] = $user;
        $this->success('登陆成功',U('Admin/Index/index'));
    }

    public function verify(){
//        C('verify')
        $Verify = new \Think\Verify();
        $Verify->length = 3;
        $Verify->codeSet = '0123456789';
        $Verify->entry();
    }

    function check_verify($code, $id = ''){
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }

    function logout(){
        $_SESSION = array();

        if (isset($_COOKIE[session_name()])) {
            cookie('token', null);
            session('[destroy]');
        }
//        dump($_COOKIE[session_name()]);
//        exit;
        $this->success('您已安全退出',U('login'));
    }
}